/**
 * @description gpg tag
 * @param signature 签名结果
 * @param author 提交人信息
 */
import React from 'react';
import { Overlay, Balloon } from '@teamix/ui';
import { YunxiaoIcon, ButtonIcon } from '@alife/devops-ui';
import docs from 'utils/docs';
import { getFeature } from 'utils/features';
import TextAvatar from '@txdfe/at-text-avatar';
import PersonalSettings from 'components/PersonalSettings';
import './index.scss';
import intl from '../../locale';

const prefix = 'gpg-tag';
const verification_status = 'verified';
const reasons = {
  unverified: intl.get({
    id: 'code-assets.components.gpgTag.GpgKeyVerificationFailed',
    defaultMessage: 'GPG 密钥验签未通过',
  }),
  same_user_different_email: intl.get({
    id: 'code-assets.components.gpgTag.TheGpgKeyHasBeen',
    defaultMessage:
      'GPG 密钥验签通过，提交者邮箱（committer email) 属于对应的云效用户，但与证书邮箱不一致',
  }),

  other_user: intl.get({
    id: 'code-assets.components.gpgTag.TheGpgKeyPassesThe',
    defaultMessage: 'GPG 密钥验签通过，但提交者邮箱（committer email) 不属于对应云效的用户',
  }),
  unverified_key: intl.get({
    id: 'code-assets.components.gpgTag.TheGpgKeyMailboxDoes',
    defaultMessage: 'GPG 密钥邮箱不属于对应的云效用户',
  }),
  unknown_key: intl.get({
    id: 'code-assets.components.gpgTag.NoMatchingGpgKeyIs',
    defaultMessage: '找不到匹配的 GPG 密钥，',
  }),
};

export default class GpgTag extends React.PureComponent {
  renderIcon = () => {
    const { signature } = this.props;
    let iconType = '';
    let iconClass = '';
    if (signature.verification_status === verification_status) {
      iconType = 'safe-line';
      iconClass = 'green';
    } else if (signature.verification_status === 'unknown_key') {
      iconType = 'cd-ziyuan1-line';
      iconClass = 'gray';
    } else {
      iconType = 'cd-circle-questionbeifen-line';
      iconClass = 'red';
    }

    return <YunxiaoIcon type={iconType} className={`${prefix}-icon-${iconClass}`} />;
  };

  renderVerifiedInfo = () => {
    const { signature, author } = this.props;
    return (
      <div className={`${prefix}-success`}>
        <div className={`${prefix}-success-user`}>
          <TextAvatar
            text={author.name || ''}
            image={author.avatar_url || ''}
            size="xs"
            radius="50%"
            needAddedText
          />
        </div>
        <div className={`${prefix}-success-key`}>
          {intl.get({
            id: 'code-assets.components.gpgTag.GpgKeyId',
            defaultMessage: 'GPG key ID：',
          })}
          {signature.gpg_key_id ? signature.gpg_key_id.toUpperCase() : ''}
        </div>
      </div>
    );
  };

  renderUnVerifiedInfo = () => {
    const { signature } = this.props;
    const isUnknow = signature.verification_status === 'unknown_key';
    return (
      <div className={`${prefix}-error`}>
        {signature.gpg_key_id && (
          <div>
            {intl.get({
              id: 'code-assets.components.gpgTag.GpgKeyId',
              defaultMessage: 'GPG key ID：',
            })}
            {signature.gpg_key_id.toUpperCase()}
          </div>
        )}
        <div>
          {reasons[signature.verification_status]}
          {getFeature('personal.settings.gpg') && isUnknow && (
            <PersonalSettings
              className="no-href-with-click"
              type="gpg"
            >
              {intl.get({ id: 'code-assets.components.gpgTag.AddNow', defaultMessage: '立即添加' })}
            </PersonalSettings>
          )}
        </div>
      </div>
    );
  };

  renderPopup = () => {
    const { signature } = this.props;
    const isVerified = signature.verification_status === verification_status;
    let barClass = '';
    let title = '';
    if (signature.verification_status === verification_status) {
      barClass = 'green';
      title = intl.get({
        id: 'code-assets.components.gpgTag.TheCurrentSubmissionHasBeen',
        defaultMessage: '当前提交已通过验证',
      });
    } else if (signature.verification_status === 'unknown_key') {
      barClass = 'gray';
      title = intl.get({
        id: 'code-assets.components.gpgTag.UnknownGpgKey',
        defaultMessage: '未知的 GPG 密钥',
      });
    } else {
      barClass = 'red';
      title = intl.get({
        id: 'code-assets.components.gpgTag.TheCurrentSubmissionFailedVerification',
        defaultMessage: '当前提交未通过验证',
      });
    }
    return (
      <div className={`${prefix}-popup overlay-shadow`}>
        <div className={`${prefix}-bar ${barClass}`} />
        <div className={`${prefix}-popup-header`}>
          <div className={`${prefix}-popup-title`}>
            <div>{title}</div>
            <Balloon
              closable={false}
              trigger={<ButtonIcon type="secondary" style={{ padding: 0 }} name="question-line" />}
              align="t"
            >
              <a target="_blank" href={docs('gpg')} rel="noreferrer">
                {intl.get({
                  id: 'code-assets.components.gpgTag.HowDoIUseGpg',
                  defaultMessage: '如何使用 GPG 签名验证？',
                })}
              </a>
            </Balloon>
          </div>
          {/* 此功能后期支持，先隐藏 */}
          {/* <div className={`${prefix}-popup-desc`}>
             创建于 Codeup 网页端 | 通过官方 GPG 密钥签名
            </div> */}
        </div>
        <div className={`${prefix}-popup-detail`}>
          {isVerified ? this.renderVerifiedInfo() : this.renderUnVerifiedInfo()}
        </div>
      </div>
    );
  };

  render() {
    const { signature } = this.props;
    if (!signature) {
      return null;
    }
    return (
      <React.Fragment>
        <Overlay.Popup trigger={this.renderIcon()} triggerType={'hover'}>
          {this.renderPopup()}
        </Overlay.Popup>
      </React.Fragment>
    );
  }
}
